﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace DigibizAdvancedMediaPicker
{
    /// <summary>
    /// Summary description for DAMP_ImagePreview
    /// </summary>
    public class DAMP_ImagePreview : IHttpHandler
    {
        string mimeType = "image/jpeg";
        string blankImage = "/umbraco/plugins/DigibizAdvancedMediaPicker/blank.gif";

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "image/jpeg";

            // Parse querystring parameters
            string imgUrl = context.Server.UrlDecode(context.Request.QueryString["img"]);
            string fallbackImgUrl = context.Server.UrlDecode(context.Request.QueryString["fallback"]);
            int imgHeight;
            int imgWidth;
            int.TryParse(context.Request.QueryString["w"], out imgWidth);
            int.TryParse(context.Request.QueryString["h"], out imgHeight);

            context.Response.Clear();
            context.Response.BufferOutput = true;

            if (!System.IO.File.Exists(context.Server.MapPath(umbraco.IO.SystemDirectories.Root + imgUrl)))
            {
               //
            }
            else 
            {
            
            
                // Get the full image
                Image fullSizeImg = Image.FromFile(context.Server.MapPath(umbraco.IO.SystemDirectories.Root + imgUrl));

                if (imgHeight > 0 && imgWidth > 0)
                {

                    if (imgHeight >= fullSizeImg.Height && imgWidth >= fullSizeImg.Width)
                    {
                        // The requested image height/width are bigger than original - just write out the original image
                        using (MemoryStream stream = new MemoryStream())
                        {
                            ((System.Drawing.Image)fullSizeImg).Save(stream, fullSizeImg.RawFormat);
                            stream.WriteTo(context.Response.OutputStream);
                        }
                    }
                    else
                    {
                        // Get image actual width/height
                        int originalWidth = fullSizeImg.Width;
                        int originalHeight = fullSizeImg.Height;

                        double newWidth = originalWidth;
                        double newHeight = originalHeight;

                        // Calculate new width & height
                        if (newWidth > imgWidth && imgWidth != 0)
                        {
                            double ratio = ((double)imgWidth) / newWidth;
                            newWidth = (newWidth * ratio);
                            newHeight = (newHeight * ratio);
                        }
                        if (newHeight > imgHeight && imgHeight != 0)
                        {
                            double ratio = ((double)imgHeight) / newHeight;
                            newWidth = (newWidth * ratio);
                            newHeight = (newHeight * ratio);
                        }

                        // Create the new image
                        Bitmap bp = new Bitmap(Convert.ToInt32(newWidth), Convert.ToInt32(newHeight));
                        Graphics g = Graphics.FromImage((System.Drawing.Image)bp);

                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                        g.DrawImage(fullSizeImg, 0, 0, bp.Width, bp.Height);

                        g.Dispose();

                        // Set compresion ratio to 90%
                        var codecParams = new EncoderParameters();
                        codecParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L);

                        // Save
                        using (MemoryStream stream = new MemoryStream())
                        {
                            try
                            {
                                if (fullSizeImg.RawFormat.Guid == ImageFormat.Png.Guid || fullSizeImg.RawFormat.Guid == ImageFormat.Gif.Guid)
                                {
                                    ((System.Drawing.Image)bp).Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                                    //test
                                    //((System.Drawing.Image)bp).Save(context.Response.OutputStream, GetEncoderInfo("image/png"), codecParams);
                                }
                                else
                                {
                                    ((System.Drawing.Image)bp).Save(stream, GetEncoderInfo(mimeType), codecParams);
                                }
                            }
                            catch (Exception ex)
                            {
                                if (!string.IsNullOrEmpty(fallbackImgUrl))
                                {
                                    Image fallbackImg = Image.FromFile(context.Server.MapPath(umbraco.IO.SystemDirectories.Root + fallbackImgUrl));
                                    ((System.Drawing.Image)fallbackImg).Save(stream, fallbackImg.RawFormat);
                                    fallbackImg.Dispose();
                                }
                                else
                                {
                                    ((System.Drawing.Image)fullSizeImg).Save(stream, fullSizeImg.RawFormat);
                                }

                            }
                            stream.WriteTo(context.Response.OutputStream);
                        }


                        bp.Dispose();
                    }
                }
                else 
                {
                    // Invalid width/height passed, write out original image
                    using (MemoryStream stream = new MemoryStream())
                    {
                        ((System.Drawing.Image)fullSizeImg).Save(stream, fullSizeImg.RawFormat);
                        stream.WriteTo(context.Response.OutputStream);
                    }
                }

                fullSizeImg.Dispose();

            }
        }

        ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            int j;
            ImageCodecInfo[] encoders;
            encoders = ImageCodecInfo.GetImageEncoders();
            for (j = 0; j <  encoders.Length; j++) 
            {//-1?
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            }
            return null;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}